package com.ruoyi.tb.lmt.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.GuidUtil;
import com.ruoyi.tb.lmt.domain.bo.TbFdxBo;
import com.ruoyi.tb.lmt.domain.bo.TbFdxdetailBo;
import com.ruoyi.tb.lmt.domain.bo.TbPreflightBo;
import com.ruoyi.tb.lmt.domain.vo.TbFdxdetailVo;
import com.ruoyi.tb.lmt.service.ITbPreflightService;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.tb.lmt.domain.vo.TbPreflightdetailVo;
import com.ruoyi.tb.lmt.domain.bo.TbPreflightdetailBo;
import com.ruoyi.tb.lmt.service.ITbPreflightdetailService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 过程验收详情
 *
 * @author ruoyi
 * @date 2024-01-03
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/xha-lmt/preflightdetail")
public class TbPreflightdetailController extends BaseController {

    private final ITbPreflightdetailService iTbPreflightdetailService;

    private final ITbPreflightService iTbPreflightService;

    /**
     * 查询过程验收详情列表
     */
    @SaCheckPermission("xha-lmt:preflightdetail:list")
    @GetMapping("/list")
    public TableDataInfo<TbPreflightdetailVo> list(TbPreflightdetailBo bo, PageQuery pageQuery) {
        return iTbPreflightdetailService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出过程验收详情列表
     */
    @SaCheckPermission("xha-lmt:preflightdetail:export")
    @Log(title = "过程验收详情", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TbPreflightdetailBo bo, HttpServletResponse response) {
        List<TbPreflightdetailVo> list = iTbPreflightdetailService.queryList(bo);
        ExcelUtil.exportExcel(list, "过程验收详情", TbPreflightdetailVo.class, response);
    }

    /**
     * 获取过程验收详情详细信息
     *
     * @param ID 主键
     */
    @SaCheckPermission("xha-lmt:preflightdetail:query")
    @GetMapping("/{ID}")
    public R<TbPreflightdetailVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long ID) {
        return R.ok(iTbPreflightdetailService.queryById(ID));
    }

    /**
     * 新增过程验收详情
     */
    @SaCheckPermission("xha-lmt:preflightdetail:add")
    @Log(title = "过程验收详情", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody TbPreflightdetailBo bo) {
        return toAjax(iTbPreflightdetailService.insertByBo(bo));
    }

    /**
     * 修改过程验收详情
     */
    @SaCheckPermission("xha-lmt:preflightdetail:edit")
    @Log(title = "过程验收详情", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody TbPreflightdetailBo bo) {
        return toAjax(iTbPreflightdetailService.updateByBo(bo));
    }

    /**
     * 删除过程验收详情
     *
     * @param IDs 主键串
     */
    @SaCheckPermission("xha-lmt:preflightdetail:remove")
    @Log(title = "过程验收详情", businessType = BusinessType.DELETE)
    @DeleteMapping("/{IDs}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] IDs) {
        return toAjax(iTbPreflightdetailService.deleteWithValidByIds(Arrays.asList(IDs), true));
    }


    @SaCheckPermission("xha-lmt:preflightdetail:addPreflight")
    @Log(title = "新增过程验收任务", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/preflight")
    public R<Void> addPreflight(@Validated(AddGroup.class) @RequestBody Map map) {
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            TbPreflightBo tbPreflight = new TbPreflightBo();
            Long Id = GuidUtil.getZcbhid();
            tbPreflight.setID(Id);
            tbPreflight.setLmtNumber((String) map.get("lmtNumber"));
            tbPreflight.setLmtType((String) map.get("lmtType"));
            String requireStartTime = (String) map.get("requireStartTime");
            if (requireStartTime!= null &&!requireStartTime.isEmpty()) {
                tbPreflight.setRequireStartTime(formatter.parse(requireStartTime));
            }
            tbPreflight.setWorkType("过程验收");
            tbPreflight.setStatus("新提票");
            LoginUser currentUser =  LoginHelper.getLoginUser();
            tbPreflight.setCreateTime(new Date());
            tbPreflight.setCreateBy(currentUser.getUsername());
            iTbPreflightService.insertByBo(tbPreflight);

            //新增
            TbPreflightdetailBo tbPreflightdetailBo = new TbPreflightdetailBo();
            tbPreflightdetailBo.setFdxId(Id);
            tbPreflightdetailBo.setWorkName((String) map.get("workName"));
            tbPreflightdetailBo.setWorkKind((String) map.get("workKind"));
            String workGroupIdString = (String) map.get("workCategoryId");
            if (workGroupIdString != null && !workGroupIdString.isEmpty()) {
                try {
                    Long workGroupId = Long.parseLong(workGroupIdString);
                    tbPreflightdetailBo.setWorkCategoryId(workGroupId);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
            tbPreflightdetailBo.setWorkCategory((String) map.get("workCategory"));
            tbPreflightdetailBo.setWorkGroup((String) map.get("workGroup"));
            tbPreflightdetailBo.setWorkGroup2((String) map.get("workGroup2"));
            tbPreflightdetailBo.setWorkCategoryRemark((String) map.get("workCategoryRemark"));
            tbPreflightdetailBo.setStatus("未提报");
            tbPreflightdetailBo.setCheckReapirReqire((String) map.get("checkReapirReqire"));
            tbPreflightdetailBo.setTaskUrl((String) map.get("taskUrl"));
            tbPreflightdetailBo.setCreateTime(new Date());
            tbPreflightdetailBo.setCreateBy(currentUser.getUsername());

            iTbPreflightdetailService.insertByBo(tbPreflightdetailBo);
            return R.ok();
        }
        catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }


    @SaCheckPermission("xha-lmt:preflightdetail:updatePreflight")
    @Log(title = "修改过程验收任务", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/updatePreflight")
    public R<Void> updatePreflight(@Validated(AddGroup.class) @RequestBody Map map) {
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            TbPreflightBo tbPreflight = new TbPreflightBo();
            Number fdxIdNumber = (Number) map.get("fdxId");
            tbPreflight.setID(fdxIdNumber.longValue());

            tbPreflight.setLmtNumber((String) map.get("lmtNumber"));
            tbPreflight.setLmtType((String) map.get("lmtType"));
            if (map.get("requireStartTime")!=null){
                tbPreflight.setRequireStartTime(formatter.parse((String) map.get("requireStartTime")));
            }
            LoginUser currentUser =  LoginHelper.getLoginUser();
            tbPreflight.setUpdateTime(new Date());
            tbPreflight.setUpdateBy(currentUser.getUsername());
            iTbPreflightService.updateByBo(tbPreflight);

            //新增
            TbPreflightdetailBo tbPreflightdetailBo = new TbPreflightdetailBo();
//            Number id = (Number) map.get("id");
//            tbPreflightdetailBo.setID(id.longValue());
            Object idObj = map.get("id");
            // 检查idObj是否为Number类型
            if (idObj instanceof Number) {
                Number idNumber = (Number) idObj;
                tbPreflightdetailBo.setID(idNumber.longValue());
            } else if (idObj instanceof String) { // 检查idObj是否为String类型
                tbPreflightdetailBo.setID(Long.parseLong((String) idObj));
            } else {
                // 抛出异常或者处理其他类型的情况
                throw new IllegalArgumentException("The type of 'id' is neither Number nor String.");
            }
            tbPreflightdetailBo.setFdxId(fdxIdNumber.longValue());
            tbPreflightdetailBo.setWorkName((String) map.get("workName"));
            tbPreflightdetailBo.setWorkKind((String) map.get("workKind"));
            tbPreflightdetailBo.setWorkCategoryId(Long.parseLong((String) map.get("workCategoryId")));
            tbPreflightdetailBo.setWorkCategory((String) map.get("workCategory"));
            tbPreflightdetailBo.setWorkCategoryRemark((String) map.get("workCategoryRemark"));
            tbPreflightdetailBo.setCheckReapirReqire((String) map.get("checkReapirReqire"));
            tbPreflightdetailBo.setRemark((String) map.get("remark"));
            tbPreflightdetailBo.setWorkGroup((String) map.get("workGroup"));
            tbPreflightdetailBo.setWorkGroup2((String) map.get("workGroup2"));
            tbPreflightdetailBo.setWorkUser((String) map.get("workUser"));
            tbPreflightdetailBo.setWorkUser2((String) map.get("workUser2"));
            tbPreflightdetailBo.setTaskUrl((String) map.get("taskUrl"));
            tbPreflightdetailBo.setUpdateTime(new Date());
            tbPreflightdetailBo.setUpdateBy(currentUser.getUsername());

            iTbPreflightdetailService.updateByBo(tbPreflightdetailBo);
            return R.ok();
        }
        catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    //查询预检任务
    @GetMapping("/list/Preflight")
    public TableDataInfo<TbPreflightdetailVo> selectPreflight(String id, String lmtType, String lmtNumber, String status, PageQuery pageQuery) {
        return iTbPreflightdetailService.selectPreflight(id,lmtType,lmtNumber,status, pageQuery);
    }

    //查询预检任务
    @GetMapping("/list/PreflightById")
    public R<TbPreflightdetailVo> selectPreflightById(String id) {
        return R.ok(iTbPreflightdetailService.selectPreflightById(id));
    }
}
